#include <QtGui>
#include <QMessageBox>
#include <iostream>
#include "../../include/gui_qt_demo/uiInclude/tabRosConn.h"

using namespace Qt;

TabRosConn::TabRosConn()
{
  ui.setupUi(this); //
  init();
}

TabRosConn::~TabRosConn(){

}


void TabRosConn::init(){
  initUi();
  slotConnect();
}

void TabRosConn::initUi(){
  tab_ = new QWidget();
  QVBoxLayout * layout = new QVBoxLayout(tab_);//铺满布局
  this->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);//铺满布局
   layout->addWidget(this);
   tab_->setLayout(layout);
}
  
void TabRosConn::dealData(){

}
///signal
void TabRosConn::rosConnSolt(bool conn){
  std::cout<<"get the ros conn:"<<conn<<std::endl;
}

///slot
void TabRosConn::useLocalNodeSlot(bool check){
  data_.setUseLocalNode(check);
}
void TabRosConn::rememberConnSlot(bool check){
  data_.setRemem(check);
}
void TabRosConn::autoConnSlot(bool check){
  data_.setAutoConn(check);
}
void TabRosConn::masterFinishedSlot(){
  data_.setRosMasterUrl(ui.ros_master_url->text().toStdString());
}
void TabRosConn::ipFinishedSlot(){
  data_.setRosIP(ui.rosip->text().toStdString());
}

void TabRosConn::rosConnDealSlot(bool conn){
  if(conn){
    ui.cb_use_mynode->setEnabled(false);
    ui.isAC->setEnabled(false);
    ui.ros_master_url->setEnabled(false);
    ui.rosip->setEnabled(false);
    ui.btn_con->setEnabled(false);
  }else{
    ui.cb_use_mynode->setEnabled(true);
    ui.isAC->setEnabled(true);
    ui.ros_master_url->setEnabled(true);
    ui.rosip->setEnabled(true);
    ui.btn_con->setEnabled(true);  
  }
}

void TabRosConn::focusInEvent(QFocusEvent *e){
  data_.rosNodeConnect(DataPtr->getRosConn());
}
void TabRosConn::connBtnSlot(){
  if(data_.getUseLocalNode()){
    if(!rosNode_.init()){
      showNoMasterMessage();
    }else{
      rosConnDealSlot(true);
    }
  }else{
    if(!rosNode_.init(data_.getRosMasterUrl(),data_.getRosIP())){
      showNoMasterMessage();
    }else{
      rosConnDealSlot(true);
    }
  }
  cout<<"clicked"<<endl;
}
void TabRosConn::cancelBtnSlot(){
  close();
}

void TabRosConn::slotConnect(){
  QObject::connect(&data_, SIGNAL(rosConnectSignals(bool)), this, SLOT(rosConnDealSlot(bool)));
  QObject::connect(ui.cb_use_mynode, SIGNAL(toggled(bool)), this, SLOT(useLocalNodeSlot(bool)));
  QObject::connect(ui.isRC, SIGNAL(toggled(bool)), this, SLOT(rememberConnSlot(bool)));
  QObject::connect(ui.isAC, SIGNAL(toggled(bool)), this, SLOT(autoConnSlot(bool)));
  
  QObject::connect(ui.ros_master_url, SIGNAL( editingFinished()), this, SLOT(masterFinishedSlot()));
  QObject::connect(ui.rosip, SIGNAL( editingFinished()), this, SLOT(ipFinishedSlot()));
  
  QObject::connect(ui.btn_con, SIGNAL(clicked()), this, SLOT(connBtnSlot()));
  QObject::connect(ui.btn_cancel, SIGNAL(clicked()), this, SLOT(cancelBtnSlot()));
}

void TabRosConn::showNoMasterMessage(){
  QMessageBox msgBox;
  msgBox.setText("Couldn't find the ros master.");
  msgBox.exec();
  close();
}
